const pool = require('../database/db'); // 确保使用promise接口
class articlesDao {
  // 根据文章id获取文章
  async getArticle(id) {
    const [rows] = await pool.query(
      'SELECT * FROM articles WHERE id = ?',
      [id]
    );
    if (rows[0]) {
      // 将 BLOB 数据转换为 base64 编码的字符串
      rows[0].image = rows[0].image ? rows[0].image.toString('base64') : null;
    }
    return rows[0] || null; // 返回单个对象或null
  }
  // 新增联表查询方法
  async getArticleWithAuthor(id) {
    const [rows] = await pool.query(
      `SELECT articles.*, users.username 
     FROM articles 
     JOIN users ON articles.author_id = users.id 
     WHERE articles.id = ?`,
      [id]
    );
    return rows[0] || null;
  }
  // 获取文章列表
  async getAllArticle(id) {
    try {
      const [rows] = await pool.query(`
        SELECT 
          id,
          title,
          content,
          image AS imageUrl,  -- 确保别名与前端匹配
          author_id,
          likes AS likeCount   -- 别名对应前端字段
        FROM articles
      `);
      return rows; // 直接返回解析后的行数据
    } catch (err) {
      console.error('DAO层错误:', err);
      throw err; // 向上抛出错误
    }
  }
  // 传入文章的标题title/content内容/用户id author_id新增文章 默认点赞数likes是0
  async addArticle(title, content, author_id) {
    try {
      let result = {}
      result = await pool.execute('insert articles(title,content,author_id,likes) values(?,?,?,?)', [title, content, author_id, 0])
      return result
    } catch (err) {
      console.log('出错:' + err)
    }
  }
  // 根据文章id 添加点赞数
  async addLikes(id) {
    try {
      let result = {}
      result = await pool.execute('update articles set likes = likes + 1 where id = ?', [id])
      return result
    } catch (err) {
      console.log('出错:' + err)
    }
  }
}
module.exports = new articlesDao()